package service

import (
	"errors"
	"fmt"
	"vrcm/src/vrcm/app/admin/models/subject"
	"vrcm/src/vrcm/common/service"
	//"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"time"

	"vrcm/src/vrcm/app/admin/service/dto/subject"
	cDto "vrcm/src/vrcm/common/dto"
)

type Subject struct {
	service.Service
}

// GetPage 获取Subject列表
func (e *Subject) GetPage(c *dto.SubjectGetPageReq, list *[]subject.Subject, count *int64) error {
	var err error
	var data subject.Subject
	//根据活动获取试卷
	ids := make([]int, 0, 10)
	c.IsDelete = 2
	if len(c.EventId) > 0 {
		e.Orm.Model(&subject.EventPaper{}).Distinct("paper_id").Select("paper_id").Where(subject.EventPaper{EventId: c.EventId, TenantId: c.TenantId}).Find(&ids)
		fmt.Println("ids", ids)
	}
	ids = append(ids, c.PaperId)
	var db *gorm.DB
	if len(ids) <= 0 {
		db = e.Orm.Model(&data)
	} else {
		db = e.Orm.Model(&data).Where("paper_id in ?", ids)
	}
	err = db.
		Scopes(
			//cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Where("is_delete = 2").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error

	if err != nil {
		e.Log.Errorf("SubjectService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// GetByPaperId 获取Subject对象
func (e *Subject) GetByPaperId(d *dto.SubjectGetByPaperIdReq) (*[]subject.Subject, error) {
	var data []subject.Subject
	err := e.Orm.Where("paper_id in ? and is_delete = ?", d.PaperIds, 2).Find(&data).Error
	if err != nil {
		e.Log.Errorf("Service GetSubject error:%s \r\n", err)
		return nil, err
	}
	return &data, nil
}

// Get 获取Subject对象
func (e *Subject) Get(d *dto.SubjectGetReq) (*subject.Subject, error) {
	var data subject.Subject
	err := e.Orm.Model(&data).Where("is_delete", 2).First(&data, d.GetId()).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		e.Log.Errorf("Service GetSubject error:%s \r\n", err)
		return nil, err
	}

	if data.Id <= 0 {
		return nil, err
	}

	return &data, nil
}

// Insert 创建Subject对象
func (e *Subject) Insert(c *dto.SubjectInsertReq) error {
	var err error
	var data subject.Subject
	var subjectOptions []subject.SubjectOption

	//新增题目判断重复
	e.Orm.Model(&subject.Subject{}).Where(&subject.Subject{SubjectName: c.SubjectName, PaperId: c.PaperId, IsDelete: 2}).First(&data)
	if data.Model.Id > 0 {
		err = errors.New("题目已经存在,请重新创建")
		e.Log.Errorf("SubjectService Insert error:%s \r\n", err)
		return err
	}
	//新增题目
	c.Generate(&data)
	tx := e.Orm.Begin()
	err = tx.Create(&data).Error
	if err != nil {
		e.Log.Errorf("SubjectService Insert error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//新增题目选项
	c.Id = data.Id
	c.Generate2(&subjectOptions)
	err = tx.Create(&subjectOptions).Error
	if err != nil {
		e.Log.Errorf("SubjectService Insert error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// Update 修改Subject对象
func (e *Subject) Update(c *dto.SubjectUpdateReq) error {
	var err error
	var data = subject.Subject{}
	var subjectOptions []subject.SubjectOption

	//修改后的题目不能重复
	e.Orm.Model(&subject.Subject{}).Where(&subject.Subject{SubjectName: c.SubjectName, PaperId: c.PaperId, IsDelete: 2}).Not("id = ?", c.Id).First(&data)
	if data.Model.Id > 0 {
		err = errors.New("题目已经存在,请重新创建")
		e.Log.Errorf("SubjectService Insert error:%s \r\n", err)
		return err
	}

	tx := e.Orm.Begin()
	tx.First(&data, c.GetId())
	c.Generate(&data, &subjectOptions)

	db := tx.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("SubjectService Save error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//先删除subject_option关联信息
	err = tx.Where(map[string]interface{}{"subject_id": data.Id}).Delete(new(subject.SubjectOption)).Error
	if err != nil {
		e.Log.Errorf("SubjectService Delete error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	err = tx.Create(subjectOptions).Error
	if err != nil {
		e.Log.Errorf("SubjectService create error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// Remove 删除Subject
func (e *Subject) Remove(d *dto.SubjectDeleteReq) error {
	//db := e.Orm.Model(&data).Delete(&data, d.GetId())
	value := make(map[string]interface{})
	value["is_delete"] = 1
	value["update_time"] = time.Now().Unix()
	err := e.Orm.Model(&subject.Subject{}).Where("id in (?)", d.GetId()).Updates(value).Error
	if err != nil {
		e.Log.Errorf("Service RemoveSubject error:%s \r\n", err)
		return err
	}

	err = e.Orm.Model(&subject.SubjectOption{}).Where("subject_id in (?)", d.GetId()).Updates(value).Error
	if err != nil {
		e.Log.Errorf("Service RemoveSubjectOption error:%s \r\n", err)
		return err
	}
	return nil
}

// GetSubjectOptions 批量获取SubjectOption对象
func (e *Subject) GetSubjectOptions(ids []int) (data *[]subject.SubjectOption, err error) {
	err = e.Orm.Model(&subject.SubjectOption{}).Where("subject_id IN ?", ids).Order("sort").Find(&data).Error
	if err != nil {
		e.Log.Errorf("Service GetSubjectOptions error:%s \r\n", err)
		return nil, err
	}
	return data, nil
}

func (e *Subject) Filter(slice []subject.SubjectOption, f func(subject.SubjectOption) bool) []subject.SubjectOption {
	var n []subject.SubjectOption
	for _, e := range slice {
		if f(e) {
			n = append(n, e)
		}
	}
	return n
}
